package com.wf.mock.app.mina.app;

import lombok.extern.log4j.Log4j;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import com.wf.mock.app.mina.MessageIntentType;
import com.wf.mock.app.mina.app.processor.impl.MainMessageProcessorImpl;
import com.wf.mock.app.mina.dto.RawMessageDTO;

@Log4j
public class AppClientHandler extends IoHandlerAdapter {

	public void messageReceived(IoSession session, Object message) throws Exception {
		session.setAttribute("lastRecieveHeartBeatTime", System.currentTimeMillis());
		String trim = message.toString().trim();

		RawMessageDTO rawMessageDTO = RawMessageDTO.create(trim);

		// log.info("cost time:" + MinaUtils.parseCostTime(rawMessageDTO.getMsgBody()) + " \r\n message" +
		// rawMessageDTO);

		MainMessageProcessorImpl.getInstance().process(rawMessageDTO, session);

	}

	@Override
	public void sessionOpened(IoSession session) throws Exception {
		session.setAttribute("lastRecieveHeartBeatTime", System.currentTimeMillis());
	}

	public void messageSent(IoSession session, Object message) throws Exception {
		// log.info(" message:" + message);
	}

	@Override
	public void sessionClosed(IoSession session) throws Exception {
		log.info("sessionClosed:" + session);
		System.exit(0);
	}

	@Override
	public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
		log.error("exceptionCaught:" + session, cause);
		System.exit(0);
	}

	@Override
	public void sessionIdle(IoSession session, IdleStatus status) throws Exception {

		if (status == IdleStatus.READER_IDLE) {
			long lastRecieveHeartBeatTime = Long.valueOf(session.getAttribute("lastRecieveHeartBeatTime", 0L)
					.toString());
			long l = System.currentTimeMillis() - lastRecieveHeartBeatTime;
			System.out.println("距离上次收到消息时间:" + l + "ms");
			if (l >= 20 * 1000 + 5000) {
				System.out.println("主动关闭session" + session);
				session.close(true);
			}
		} else if (status == IdleStatus.WRITER_IDLE) {
			session.write(MessageIntentType.HEARTBEAT.getPreffix() + "{}");
		}

	}
}
